package com.asw.springboot.common.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.asw.springboot.common.result.GlobalErrorInfoEnum;
import com.asw.springboot.common.result.ResultBody;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


import java.util.Arrays;
import java.util.Map;

/*@ControllerAdvice*/
public class GlobalExceptionHandler {
	private static final Logger logger = Logger.getLogger(GlobalExceptionHandler.class);

	public String currentVersion;
	protected HttpServletRequest request;
	protected HttpServletResponse response;

	@ModelAttribute
	public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}



	/*@ExceptionHandler(value = ApiException.class)
	@ResponseBody*/
	public ResultBody exp(Exception ex) {
		// 记录日志
		logger.error("调用API接口出现异常：" + request.getRequestURL() +" 请求方式:"+ request.getMethod()+"  "+getRequestAsg(request)
				+",版本号：" + getCurrentVersion() +  ",设备：" +getCurrentDeviceType()+
				",错误信息为:"+ex.toString());
		return new ResultBody(GlobalErrorInfoEnum.SYS_ERROR);
	}


	/*@ExceptionHandler(value = AdminException.class)*/
	public ModelAndView procAdminError(Exception ex) {
		// 记录日志
		logger.error("调用API接口出现异常：" + request.getRequestURL() +" 请求方式:"+ request.getMethod()+"  "+getRequestAsg(request)
				+",版本号：" + getCurrentVersion() + ",设备：" + getCurrentDeviceType()+
				",错误信息为:"+ex.toString());
		ModelAndView mv = new ModelAndView();
		mv.setViewName("error500");
		return mv;
	}



	/***
	 * 得到 request请求参数
	 * @param request
	 * @return
	 */
	public String getRequestAsg(HttpServletRequest request){
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()){
			sb.append("参数名:").append(entry.getKey()).append("-参数值:").append(Arrays.toString(entry.getValue()));
		}
		return sb.toString();
	}





	/**
	 * 当前版本号去掉点
	 *
	 * @return
	 */
	public String getCurrentVersion() {
		currentVersion = request.getParameter("currentVersion");
		if (!StringUtils.isEmpty(currentVersion)) {
			currentVersion = currentVersion.trim().replace(".", "");
		}
		return currentVersion;
	}

	/**
	 * 当前设备
	 *
	 * @return
	 */
	public String getCurrentDeviceType() {
		return request.getParameter("currentDeviceType");
	}

}
